package com.common.frame.permission


import android.content.pm.PackageManager
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment

class PermissionFragment : Fragment() {

    private var callback: PermissionHelper.PermissionListener? = null
    private val grantedList: MutableList<String> = mutableListOf()
    private val deniedList: MutableList<String> = mutableListOf()


    //去设置页面的回调
    private val settingLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            for (index in (deniedList.size - 1) downTo 0) {
                if (ContextCompat.checkSelfPermission(
                        requireActivity(),
                        deniedList[index]
                    ) == PackageManager.PERMISSION_GRANTED
                ) {
                    grantedList.add(deniedList[index])
                    deniedList.removeAt(index)
                }
            }
        }

    //权限请求的回调
    private val permissionsLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->
            //过滤 value 为 false 的元素并转换为 list
            val deniedList = result.filter { !it.value }.map { it.key }
            callback?.onAllAllowed?.invoke(deniedList.isEmpty())
            when {
                deniedList.isNotEmpty() -> {
                    callback?.onRefuse?.invoke(deniedList)
                }
                else -> callback?.onAllow?.invoke()
            }
        }

    fun request(
        permissions: Array<String>,
        listener: PermissionHelper.PermissionListener
    ) {
        callback = listener
        permissionsLauncher.launch(permissions)
    }


    private fun shouldShowRequestPermissionsRationale(permissions: Array<String>): Boolean {
        permissions.forEach {
            if (shouldShowRequestPermissionRationale(it)) {
                return true
            }
        }
        return false
    }

}